package com.yanqu.road.server.gameplayer.module.activity.shanshui;

import com.yanqu.road.dao.impl.activity.xingyoushanshui.XingYouShanShuiUserDataDaoImpl;
import com.yanqu.road.entity.activity.youxing.XingYouShanShuiUserData;
import com.yanqu.road.entity.activity.youxing.config.XingYouConfig;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiEventInfo;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiGridInfo;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiRoleInfo;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.player.UserBeauty;
import com.yanqu.road.exception.BusinessException;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.pb.activity.CommonTeamProto;
import com.yanqu.road.pb.activity.XingYouShanShuiProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.commonteam.CommonTeamMgr;
import com.yanqu.road.server.manger.activity.shanshui.XingYouShanShuiMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.List;

public class XingYouShanShuiModule extends GeneralModule {

    private XingYouShanShuiUserData userData;

    public XingYouShanShuiModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        XingYouConfig youConfig = XingYouShanShuiMgr.getConfig();
        if (youConfig != null && ActivityMgr.activityInShowTime(youConfig.getActivityInfo())) {
            userData = new XingYouShanShuiUserDataDaoImpl().getXingYouShanShuiUserData(youConfig.getActivityInfo().getActivityId(), player.getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if(userData != null){
            if(userData.isInsertOption()){
                new XingYouShanShuiUserDataDaoImpl().add(userData);
            }else if(userData.isUpdateOption()){
                new XingYouShanShuiUserDataDaoImpl().update(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        activityReload();

        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if(userData != null && config != null){
            int groupId = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), player.getUserId());
            userData.setGroupId(groupId);
            if(userData.getGroupId() >= 0) {
                XingYouShanShuiProto.CrossShanShuiUserLoginReq.Builder crossReq = XingYouShanShuiProto.CrossShanShuiUserLoginReq.newBuilder();
                crossReq.setActivityId(config.getActivityInfo().getActivityId());
                player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_USER_LOGIN, crossReq, config.getActivityInfo().getActivityId());
            }
        }
    }

    public void activityReload(){
        // 初始化
        initUserData();

        syncConfig();


    }

    public void syncConfig() {
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {

            XingYouShanShuiProto.ShanShuiConfigSyncMsg.Builder builder = XingYouShanShuiProto.ShanShuiConfigSyncMsg.newBuilder();
            int activityId = config.getActivityInfo().getActivityId();

            for (XingYouShanShuiEventInfo eventInfo : config.getEventInfoList()) {
                XingYouShanShuiProto.ShanShuiEventConfigTemp.Builder tempBuilder = XingYouShanShuiProto.ShanShuiEventConfigTemp.newBuilder();
                tempBuilder.setActivityId(activityId);
                tempBuilder.setId(eventInfo.getId());
                tempBuilder.setEmotion(eventInfo.getEmotion());
                tempBuilder.setWeight(eventInfo.getWeight());
                tempBuilder.addAllParam(eventInfo.getParam());
                tempBuilder.setName(ServerLanguageMgr.getContent(eventInfo.getName(), player.getLanguage()));
                tempBuilder.setDesc(ServerLanguageMgr.getContent(eventInfo.getDesc(), player.getLanguage()));
                builder.addEventConfig(tempBuilder);
            }

            for (XingYouShanShuiGridInfo gridInfo : config.getGridInfoList()) {
                XingYouShanShuiProto.ShanShuiGridConfigTemp.Builder tempBuilder = XingYouShanShuiProto.ShanShuiGridConfigTemp.newBuilder();
                tempBuilder.setActivityId(activityId);
                tempBuilder.setId(gridInfo.getId());
                tempBuilder.setReward1(gridInfo.getReward1());
                tempBuilder.setReward2(gridInfo.getReward2());
                tempBuilder.setReward3(gridInfo.getReward3());
                tempBuilder.setRewardShow(gridInfo.getRewardShow());
                tempBuilder.setTriggerType(gridInfo.getTriggerType());
                tempBuilder.setSort(gridInfo.getSort());
                tempBuilder.setType(gridInfo.getType());
                tempBuilder.setName(ServerLanguageMgr.getContent(gridInfo.getName(), player.getLanguage()));
                tempBuilder.setDesc(ServerLanguageMgr.getContent(gridInfo.getDesc(), player.getLanguage()));
                tempBuilder.addAllParam(gridInfo.getParam());
                tempBuilder.setEmotion(gridInfo.getEmotion());
                tempBuilder.setQuality(gridInfo.getQuality());
                builder.addGridConfig(tempBuilder);
            }

            for (XingYouShanShuiRoleInfo roleInfo : config.getRoleInfoList()) {
                XingYouShanShuiProto.ShanShuiRoleConfigTemp.Builder tempBuilder = XingYouShanShuiProto.ShanShuiRoleConfigTemp.newBuilder();
                tempBuilder.setActivityId(activityId);
                tempBuilder.setId(roleInfo.getId());
                tempBuilder.setPrice(roleInfo.getPrice());
                tempBuilder.addAllSkillParam(roleInfo.getSkillParam());
                tempBuilder.addAllDice(roleInfo.getDice());
                tempBuilder.setName(ServerLanguageMgr.getContent(roleInfo.getName(), player.getLanguage()));
                tempBuilder.setSkillName(ServerLanguageMgr.getContent(roleInfo.getSkillName(), player.getLanguage()));
                tempBuilder.setSkillDesc(ServerLanguageMgr.getContent(roleInfo.getSkillDesc(), player.getLanguage()));
                tempBuilder.setRoleDesc(ServerLanguageMgr.getContent(roleInfo.getRoleDesc(), player.getLanguage()));
                builder.addRoleConfig(tempBuilder);
            }

            player.sendPacket(Protocol.U_XING_YOU_SHAN_SHUI_SYNC_CONFIG, builder);

            if(Config.isDebug()){
                CommonTeamProto.CommonTeamGetUserDataReqMsg.Builder reqMsg = CommonTeamProto.CommonTeamGetUserDataReqMsg.newBuilder();
                reqMsg.setActivityId(config.getActivityInfo().getActivityId());
                reqMsg.setPower(getPower(config.getActivityInfo().getActivityId()));
                reqMsg.setUserInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
                try {
                    CommonTeamMgr.getUserData(player, reqMsg.build());
                } catch (BusinessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 初始化玩家数据
     */
    private synchronized void initUserData() {
        // 系统未解锁
        if (!SystemOpenMgr.systemOpen(player, eSystemId.XingYouShanShui.getValue())) {
            return;
        }
        XingYouConfig config = XingYouShanShuiMgr.getConfig();

        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {

            if (userData == null || config.getActivityInfo().getActivityId() != userData.getActivityId()) {

                XingYouShanShuiUserData shanShuiUserData = new XingYouShanShuiUserData();
                shanShuiUserData.setActivityId(config.getActivityInfo().getActivityId());
                shanShuiUserData.setUserId(player.getUserId());
                shanShuiUserData.setGroupId(-1);
                int groupId = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), player.getUserId());
                shanShuiUserData.setGroupId(groupId);

                shanShuiUserData.setInsertOption();
                userData = shanShuiUserData;
            }
        }
    }

    public int enter() {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        int groupId = GameUnionActivityGroupMgr.getGroupId(userData.getActivityId(), player.getUserId());
        if(groupId == UnionActivityGroupHelper.NO_GROUP_ID){
            XingYouShanShuiProto.ShanShuiEnterRsp.Builder clientMsg = XingYouShanShuiProto.ShanShuiEnterRsp.newBuilder();
            clientMsg.setRet(0);
            player.sendPacket(Protocol.U_XING_YOU_SHAN_SHUI_ENTER, clientMsg);
            return 0;
        }
        XingYouShanShuiProto.ShanShuiEnterReq.Builder crossReq = XingYouShanShuiProto.ShanShuiEnterReq.newBuilder();
        crossReq.setActivityId(XingYouShanShuiMgr.getActivityId());
        player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_ENTER, crossReq, userData.getActivityId());
        return 0;
    }

    //进入地图
    public int enterMap(XingYouShanShuiProto.ShanShuiEnterMapReq req) {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        XingYouShanShuiProto.CrossShanShuiEnterMapReq.Builder crossReq = XingYouShanShuiProto.CrossShanShuiEnterMapReq.newBuilder();
        crossReq.setActivityId(req.getActivityId());
        crossReq.setLanguage(player.getLanguage());
        crossReq.setReq(req);
        crossReq.setUserBaseInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
        player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_ENTER_MAP, crossReq, userData.getActivityId());
        return 0;
    }

    public int dice(XingYouShanShuiProto.ShanShuiDiceReq req) {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if(config == null){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        //休息期判断
        long todayZeroTimeStamp = DateHelper.getTodayZeroTimeStamp();
        long nowTimes = System.currentTimeMillis();
        if(nowTimes < todayZeroTimeStamp + config.getSHANSHUI_FIGHT_TIME().get(0) * DateHelper.MINUTE_MILLIONS ||
            nowTimes > todayZeroTimeStamp + config.getSHANSHUI_FIGHT_TIME().get(1) * DateHelper.MINUTE_MILLIONS){
            return GameErrorCode.E_XING_YOU_SHAN_SHUI_IN_REST_TIME;
        }

        int diceType = req.getDiceType();
        if(diceType < 1 || diceType > 5){
            return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
        }
        //专属
        if(diceType == 2){
            Property property = new Property();
            property.addProperty(config.getSHANSHUI_EXCLUSIVE_DICE_ID(), 1);
            if(!player.getModule(CurrencyModule.class).currencyIsEnough(property)){
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            player.getModule(PreReduceModule.class).preReduce(property);
        }else if(diceType == 3){
            //自选
            Property property = new Property();
            property.addProperty(config.getSHANSHUI_MECHANICAL_DICE_ID(), 1);
            if(!player.getModule(CurrencyModule.class).currencyIsEnough(property)){
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            if(req.hasDice()){
                int dice = req.getDice();
                if(dice < 1 || dice > 6){
                    return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
                }
            }
            player.getModule(PreReduceModule.class).preReduce(property);
        }
        XingYouShanShuiProto.CrossShanShuiDiceReq.Builder crossReq = XingYouShanShuiProto.CrossShanShuiDiceReq.newBuilder();
        crossReq.setActivityId(config.getActivityInfo().getActivityId());
        crossReq.setReq(req);
        long count = player.getModule(BagModule.class).getUserBagItemCount(config.getSHANSHUI_PASS_ID());
        crossReq.setTongXingNum((int)count);
        player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_DICE, crossReq, userData.getActivityId());
        return 0;
    }

    /**
     * 获取战力
     * @param activityId
     * @return
     */
    public long getPower(int activityId) {
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        //获取前30门客战力
        long power = 0;
        List<UserBeauty> topAbilityBeauty = player.getModule(BeautyModule.class).getTopIntimacyBeauty(config.getBATTLE_BEAUTY_NUM(), 3);
        for (UserBeauty beauty : topAbilityBeauty) {
            //转换计算
            long beautyPower = config.transformPatronsPower(beauty.getTotalIntimacy() + beauty.getTotalGlamour());
            power += beautyPower;
        }
        return power;
    }

    /**
     * 同步战力
     */
    public int uploadBeautyAbility(boolean needBack) {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if(config == null){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        List<UserBeauty> topAbilityBeauty = player.getModule(BeautyModule.class).getTopIntimacyBeauty(config.getBATTLE_BEAUTY_NUM(), 3);
        XingYouShanShuiProto.CrossShanShuiBattleDataUpload.Builder upload = XingYouShanShuiProto.CrossShanShuiBattleDataUpload.newBuilder();
        upload.setActivityId(config.getActivityInfo().getActivityId());
        for (UserBeauty beauty : topAbilityBeauty) {
            XingYouShanShuiProto.ShanShuiBeautyDetailInfo.Builder builder = XingYouShanShuiProto.ShanShuiBeautyDetailInfo.newBuilder();
            builder.setBeautyId(beauty.getBeautyId());
            builder.setSkinId(beauty.getSkinId());
            builder.setMacy(beauty.getTotalIntimacy());
            builder.setMour(beauty.getTotalGlamour());
            builder.setAdd(0);
            builder.setQuality(beauty.getQuality());
            upload.addDetail(builder);
        }
        upload.setNeedBack(needBack);
        player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_BATTLE_DATA_UPLOAD, upload, userData.getActivityId());
        return 0;
    }

    public XingYouShanShuiUserData getUserData() {
        return userData;
    }


    public int leave() {
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if(config == null){
            return 0;
        }
        XingYouShanShuiProto.ShanShuiLeaveReq.Builder req = XingYouShanShuiProto.ShanShuiLeaveReq.newBuilder();
        req.setActivityId(config.getActivityInfo().getActivityId());
        player.sendUnionActivityGroupPacket(Protocol.C_XING_YOU_SHAN_SHUI_LEAVE, req, config.getActivityInfo().getActivityId());
        return 0;
    }

    /**
     * 扩展图换金页子
     * @param num
     */
    public int exchangeGold(int num) {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        XingYouConfig config = XingYouShanShuiMgr.getConfig();
        if(config == null){
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }
        if(num <= 0){
            return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
        }
        long itemCount = player.getModule(BagModule.class).getUserBagItemCount(config.getSHANSHUI_EXPANSION_PLAN_ID());
        if(itemCount < num){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        Property consume = new Property();
        consume.addProperty(config.getSHANSHUI_EXPANSION_PLAN_ID(), BigInteger.valueOf(num));
        if(!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.XingYouShanShuiActivity, eLogMoneyType.XingYouShanShuiExpansionExchangeConsume)){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        Property reward = PropertyHelper.parseStringToProperty(config.getSHANSHUI_EXPANSION_PLAN_RECYCLE());
        reward.rideProperty(num);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.XingYouShanShuiActivity, eLogMoneyType.XingYouShanShuiExpansionExchangeReward);

        XingYouShanShuiProto.ShanShuiExpansionUseRsp.Builder clientMsg = XingYouShanShuiProto.ShanShuiExpansionUseRsp.newBuilder();
        clientMsg.setRet(0);
        clientMsg.setReward(PropertyHelper.parsePropertyToString(reward));
        player.sendPacket(Protocol.U_XING_YOU_SHAN_SHUI_EXPANSION_RECYCLE, clientMsg);
        return 0;
    }
}
